/* Copyright (c) 2011-2013 ISP RAS, Moscow. For more information please write to
 
      mermakov@ispras.ru
      svartanov@ispras.ru

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package ru.ispras.coffeemachine.instrument;

import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.GOTO_W;
import org.apache.bcel.generic.IfInstruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.MethodGen;

/**
 * Custom {@link MethodGen} to address minor instrumentation issue
 * 
 * @author Mikhail Ermakov (mermakov@ispras.ru)
 * @version 1.2.0
 * @since 2012-10-24
 */

@SuppressWarnings("serial")
public class CoffeeMethodGen extends MethodGen {
	
	public CoffeeMethodGen(Method method, String className, ConstantPoolGen cpg) {

		super(method, className, cpg);

	}

	@Override
	public LocalVariableTable getLocalVariableTable(ConstantPoolGen cpg) {

		return new LocalVariableTable(	cp.addUtf8("LocalVariableTable"),
										2,
										null,
										cpg.getConstantPool());
	}
	
	public boolean isConstructor() {
		
		return getName().equals("<init>");
	}
	
	public void fixLongJumps() {
		
		InstructionList il = getInstructionList();
		il.setPositions();
		InstructionHandle ih = il.getStart();
		while (ih != null) {
			if (ih.getInstruction() instanceof IfInstruction) {
				IfInstruction instruction = (IfInstruction)ih.getInstruction();
				if (instruction.getTarget() != null) {
					if (Math.abs(ih.getPosition() - instruction.getTarget().getPosition()) >= Short.MAX_VALUE) {
						IfInstruction modifiedIfInstruction = instruction.negate();
						InstructionHandle gotoHandle = il.append(ih, new GOTO_W(instruction.getTarget()));
						modifiedIfInstruction.setTarget(gotoHandle);
						ih.setInstruction(modifiedIfInstruction);
					}
				}
			}
			ih = ih.getNext();
		}
		il.update();
	}

}
